package cn.rkylin.oms.order.adapter;

import cn.rkylin.core.IDataBaseFactory;
import cn.rkylin.core.utils.StringUtil;
import cn.rkylin.oms.common.dto.DBLog;
import cn.rkylin.oms.common.utils.LogUtil;
import cn.rkylin.oms.common.utils.DateUtil;
import cn.rkylin.oms.common.utils.TaobaoEncrypt;
import cn.rkylin.oms.order.domain.*;
import cn.rkylin.oms.order.domain.taobao.*;
import cn.rkylin.oms.order.service.OrderServiceImpl;
import cn.rkylin.oms.order.vo.TaoBaoOrder;
import cn.rkylin.oms.order.vo.Trade;
import cn.rkylin.oms.refund.domain.RefundStatusMap;
import cn.rkylin.oms.system.shop.domain.Shop;
import cn.rkylin.oms.system.shop.service.IShopService;
import cn.rkylin.oms.system.shop.vo.ShopVO;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 淘宝订单适配器
 * 在原有TaobaoOrderAdapter类上修改整理而来
 *
 * @author 李明
 * @version 1.0
 * @created 2017-12-15
 */
@Scope("prototype")
@Service("taobaoOrderAdapterWithoutSplit")
public class TaobaoOrderAdapterWithoutSplit extends OrderAdapter {

    @Autowired
    private LogUtil logUtil;

    private static final Log logger = LogFactory.getLog(TaobaoOrderAdapterWithoutSplit.class);

    /**
     * 数据库访问对象
     */
    @Autowired
    private IDataBaseFactory dao;

    @Autowired
    private TaobaoOrderService taobaoOrderService;

    @Autowired
    private TaobaoTradeService taobaoTradeService;

    @Autowired
    private OrderServiceImpl orderServiceImpl;

    @Autowired
    private IShopService shopService;

    /**
     * 淘宝加密类依赖
     */
    TaobaoEncrypt taobaoEncrypt = null;

    /**
     * 测试环境开关
     */
    private Boolean isTest = false;

    /**
     * 缓存省市区数据
     */
    private static Map<String, String> AREA_CODE_MAP_CACHE = null;

    public void finalize() throws Throwable {
        super.finalize();
    }

    /**
     * 构造函数
     */
    public TaobaoOrderAdapterWithoutSplit() {
    }

    /**
     * 根据tid或者buyerNick下载平台订单
     *
     * @param mapParm
     * @return
     * @throws Exception
     */
    public int download(Map<String, String> mapParm) throws Exception {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        ShopVO shop = getShop(mapParm.get("shopId"));

        // shop取得失败的时候，返回
        if (shop == null) {
            return 0;
        }

        // 实例化加密类
        taobaoEncrypt = new TaobaoEncrypt(shop.getAppKey(),shop.getAppSecret(),shop.getSessionKey(),shop.getApiUrl());

        // 设置参数
        if (StringUtils.isNotBlank(mapParm.get("ecTradeCode"))) {
            paramMap.put("tid", mapParm.get("ecTradeCode"));
        }
        if (StringUtils.isNotBlank(mapParm.get("buyerNick"))) {
            // rds里存的buyerNick是密文，这里要加密一下，去rds匹配
            String encryptbuyerNick = taobaoEncrypt.encrypt(mapParm.get("buyerNick").toString(),"simple");
            encryptbuyerNick = StringUtils.substring(encryptbuyerNick,0,StringUtils.length(encryptbuyerNick)-4);
            paramMap.put("buyerNick", encryptbuyerNick);

        }
        paramMap.put("shop", shop);

        // 加载省市区数据缓存
        boolean loadAreaCodeCacheMapResult = loadAreaCodeCacheMap();
        if (!loadAreaCodeCacheMapResult) {
            return 0;
        }

        // 获取trade,order 列表
        List<TaoBaoOrder> taobaoOrdersJsonFromRds = new ArrayList<TaoBaoOrder>();
        this.getOrderVisitor().getOrderObjectList(paramMap, 0, 1000, taobaoOrdersJsonFromRds);
        int result = 0;
        try {
            // 保存当前页数据
            SavePageData(shop, taobaoOrdersJsonFromRds);
            result = 1;
        } catch (Exception ex) {
            logUtil.info(new DBLog(shop.getShopAccount(), "单个下载淘宝订单",
                    "单个下载淘宝订单", "tid=" + mapParm.get("ecTradeCode")));
        }
        return result;
    }


    /**
     * 订单下载
     *
     * @param shopId        店铺id
     * @param dateTimeStart 开始时间
     * @param dateTimeEnd   结束时间
     * @return
     * @throws Exception
     */
    @Override
    public int download(String shopId, String dateTimeStart, String dateTimeEnd) throws Exception {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        ShopVO shop = getShop(shopId);

        String jobId = UUID.randomUUID().toString();

        // 这里重新设置开始时间和结束时间
        dateTimeStart = DateUtil.formatDate(shop.getJobEcTradeLastUpdateTime());
        dateTimeEnd = DateUtil.getCurrentDateStr("yyyy-MM-dd HH:mm:ss");


        logUtil.info(new DBLog(shop.getShopAccount(), "自动下载淘宝订单任务开始执行,jobId=" + jobId,
                "自动下载淘宝订单", "shopId=" + shopId + ",start=" + dateTimeStart + ",end=" + dateTimeEnd));

        // shop取得失败的时候，返回
        if (shop == null) {
            return 0;
        }



        // 设置参数
        if (StringUtils.isNotBlank(dateTimeStart)) {
            paramMap.put("startTime", dateTimeStart);
        }
        if (StringUtils.isNotBlank(dateTimeEnd)) {
            paramMap.put("endTime", dateTimeEnd);
        }
        paramMap.put("shop", shop);

        // 实例化加密类
        taobaoEncrypt = new TaobaoEncrypt(shop.getAppKey(),shop.getAppSecret(),shop.getSessionKey(),shop.getApiUrl());

        // 加载省市区数据缓存
        boolean loadAreaCodeCacheMapResult = loadAreaCodeCacheMap();
        if (!loadAreaCodeCacheMapResult) {
            return 0;
        }

        // 分页保存全部数据
        int result = saveAllData(paramMap, 0, shop);

        // 更新最后执行时间
        ShopVO shopUpdate = new ShopVO();
        shopUpdate.setShopId(shopId);
        shopUpdate.setJobEcTradeLastUpdateTime(StringUtil.strToDateTime(dateTimeEnd));
        shopService.update(shopUpdate);

        logUtil.info(new DBLog(shop.getShopAccount(), "自动下载淘宝订单任务结束执行,jobId=" + jobId,
                "自动下载淘宝订单", "shopId=" + shopId + ",start=" + dateTimeStart + ",end=" + dateTimeEnd));
        return result;
    }

    /**
     * 加载省市区数据缓存
     *
     * @throws Exception
     */
    private boolean loadAreaCodeCacheMap() {
        boolean result;
        try {
            // 缓存地区码数据
            Map<String, Object> map = new HashMap<String, Object>();
            if (AREA_CODE_MAP_CACHE == null) {
                AREA_CODE_MAP_CACHE = new HashMap();
                List<AreaCode> areaCodeList = dao.findList("selectcAllAreaCode", map);
                for (AreaCode areaCode : areaCodeList) {
                    AREA_CODE_MAP_CACHE.put(StringUtils.trimToEmpty(areaCode.getProvName()) + ":" + StringUtils.trimToEmpty(areaCode.getCityName()) + ":" + StringUtils.trimToEmpty(areaCode.getDistName()), StringUtils.trimToEmpty(areaCode.getAreaCode()));
                }
            }
            result = true;
        } catch (Exception ex) {
            logUtil.error(new DBLog("", "加载省市区数据缓存失败",
                    "自动下载淘宝订单", ex.getMessage()), ex);
            result = false;
        }
        return result;
    }

    /**
     * 分页保存全部数据
     *
     * @param paramMap
     * @param loop
     * @param shop
     */
    public int saveAllData(Map<String, Object> paramMap, Integer loop, ShopVO shop) {
        List<TaoBaoOrder> taobaoOrdersJsonFromRds = new ArrayList<TaoBaoOrder>();
        if (loop == 0) { // 第一次
            getOrderVisitor().getOrderObjectList(paramMap, 0, 30, taobaoOrdersJsonFromRds);
            logger.info(shop.getShopAccount()+ "-RDS第0次获取数据条数:" + taobaoOrdersJsonFromRds.size());

            logUtil.info(new DBLog(shop.getShopAccount(), "分页保存全部数据",
                    "自动下载淘宝订单", "startRow:0;获取数据条数:" + taobaoOrdersJsonFromRds.size()));
        } else { // 之后
            getOrderVisitor().getOrderObjectList(paramMap, loop, 30, taobaoOrdersJsonFromRds);
            logUtil.info(new DBLog(shop.getShopAccount(), "分页保存全部数据",
                    "自动下载淘宝订单", "startRow:"+loop+";"+"获取数据条数:" + taobaoOrdersJsonFromRds.size()));
        }

        // 保存当前页数据
        SavePageData(shop, taobaoOrdersJsonFromRds);

        if (taobaoOrdersJsonFromRds.size() == 30) { // 查到30个就继续往下查，小于30个就是查完了
            saveAllData(paramMap, loop + 30, shop);
        }
        return 1;
    }

    /**
     * 保存一页数据
     *
     * @param shop
     * @param taobaoOrdersJsonFromRds
     */
    private void SavePageData(ShopVO shop, List<TaoBaoOrder> taobaoOrdersJsonFromRds) {

        logger.info(shop.getShopAccount()+ "-保存一页数据开始:" + taobaoOrdersJsonFromRds.size());

        // 循环每一个Trade
        for (TaoBaoOrder taoBaoOrderJsonFromRds : taobaoOrdersJsonFromRds) {

            logger.info(shop.getShopAccount()+ "-保存一页数据循环里:" + taoBaoOrderJsonFromRds.getTid());

            logUtil.info(new DBLog(shop.getShopAccount(), "自动下载淘宝订单任务单条执行开始",
                    "自动下载淘宝订单", "tid:" + taoBaoOrderJsonFromRds.getTid()));

            try {
                // 生成TopTrade
                TopTrade topTrade = getTopTradeFromJson(taoBaoOrderJsonFromRds);
                // 保存TopTrade
                saveTopTrade(topTrade);

                // 生成TopOrders
                List<TopOrder> topOrders = getTopOrdersFromJson(taoBaoOrderJsonFromRds, topTrade);
                // 保存TopOrders
                saveTopOrders(topTrade, topOrders);

                List<TopTradeOrder> listTopTradeOrder = new ArrayList<TopTradeOrder>();
                TopTradeOrder topTradeOrder = new TopTradeOrder();
                topTradeOrder.setTopTrade(topTrade);

                topTradeOrder.setListTopOrder(topOrders);
                listTopTradeOrder.add(topTradeOrder);

                //保存EcTrade
                saveEcData(listTopTradeOrder, shop);
            } catch (Exception ex) {
                logUtil.error(new DBLog(shop.getShopAccount(), "自动下载淘宝订单任务单条执行失败",
                        "自动下载淘宝订单", "tid:"+taoBaoOrderJsonFromRds.getTid()+";"+taoBaoOrderJsonFromRds.getTaoBaoResponse().getTrade_fullinfo_get_response().toString()), ex);
            }
        }
    }

    /**
     * 从Json中获取获取TopTrade
     *
     * @param taoBaoOrderJsonFromRds
     * @return
     */
    private TopTrade getTopTradeFromJson(TaoBaoOrder taoBaoOrderJsonFromRds) {
        TopTrade topTrade = new TopTrade();
        if (taoBaoOrderJsonFromRds != null && taoBaoOrderJsonFromRds.getTaoBaoResponse() != null
                && taoBaoOrderJsonFromRds.getTaoBaoResponse().getTrade_fullinfo_get_response() != null) {
            // 取得trade
            Trade trade = taoBaoOrderJsonFromRds.getTaoBaoResponse().getTrade_fullinfo_get_response().getTrade();

            // 生成oms_top_trade的主键
            String tradeId = java.util.UUID.randomUUID().toString().replaceAll("-", "");

            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                topTrade.setTopTradeId(tradeId);
                topTrade.setAdjustFee(trade.getAdjust_fee());
                topTrade.setBuyerAlipayNo(trade.getBuyer_alipay_no());
                topTrade.setBuyerMessage(trade.getBuyer_message());
                topTrade.setBuyerCodFee(trade.getBuyer_cod_fee());
                topTrade.setBuyerNick(trade.getBuyer_nick());
                topTrade.setBuyerRate("true".equals(trade.getBuyer_rate()) ? 1 : 0);
                topTrade.setCreated(sdf.parse(trade.getCreated()));
                topTrade.setPostFee(trade.getPost_fee());
                topTrade.setDiscountFee(trade.getDiscount_fee());
                topTrade.setModified(sdf.parse(trade.getModified()));
                topTrade.setConsignTime(trade.getConsign_time() != null ? sdf.parse(trade.getConsign_time()) : null);
                topTrade.setNum(trade.getNum());
                topTrade.setPayTime(trade.getPay_time() != null ? sdf.parse(trade.getPay_time()) : null);
                topTrade.setEndTime(trade.getEnd_time() != null ? sdf.parse(trade.getEnd_time()) : null);
                topTrade.setPayment(trade.getPayment());
                topTrade.setPicPath(trade.getPic_path());
                topTrade.setPostFee(trade.getPost_fee());
                topTrade.setPrice(trade.getPrice());
                topTrade.setReceivedPayment(trade.getReceived_payment());
                topTrade.setReceiverAddress(trade.getReceiver_address());
                topTrade.setReceiverCity(trade.getReceiver_city());
                topTrade.setReceiverDistrict(trade.getReceiver_district());
                topTrade.setReceiverMobile(trade.getReceiver_mobile());
                topTrade.setReceiverPhone(trade.getReceiver_phone());
                topTrade.setReceiverName(trade.getReceiver_name());
                topTrade.setReceiverState(trade.getReceiver_state());
                topTrade.setReceiverZip(trade.getReceiver_zip());
                topTrade.setSellerFlag(trade.getSeller_flag());
                topTrade.setSellerMemo(trade.getSeller_memo());
                topTrade.setSellerNick(trade.getSeller_nick());
                topTrade.setSellerRate("true".equals(trade.getSeller_rate()) ? Integer.valueOf(1) : Integer.valueOf(0));
                topTrade.setShippingType(trade.getShipping_type());
                topTrade.setStatus(trade.getStatus());
                topTrade.setTid(trade.getTid());
                topTrade.setTitle(trade.getTitle());
                topTrade.setTotalFee(trade.getTotal_fee());
                topTrade.setTradeFrom(trade.getTrade_from());
                topTrade.setType(trade.getType());
            } catch (Exception ex) {
                logUtil.error(new DBLog(topTrade.getTid().toString(), "从Json中获取获取TopTrade", "自动下载淘宝订单", "getTopTradeFromJson方法异常：" + ex.getMessage()), ex);
                return null;
            }
        }
        return topTrade;
    }

    /**
     * 保存数据到oms_top_trade
     *
     * @param topTrade
     * @return
     */
    private int saveTopTrade(TopTrade topTrade) {
        try {
            // 如果存在的场合
            TopTrade trade = (TopTrade) dao.find("selectByTidTopTrade", topTrade.getTid().toString());
            if (trade == null) {
                dao.insert("insertSelectiveTopTrade", topTrade);
            } else {
                dao.update("updateByTidSelectiveTopTrade", topTrade);
            }
        } catch (Exception ex) {
            logUtil.error(new DBLog(topTrade.getTid().toString(), "保存TopTrade", "自动下载淘宝订单", "saveTopTrade方法异常：" + ex.getMessage()), ex);
            return 0;
        }
        return 1;
    }

    /**
     * 从Json中获取获取TopOrders
     *
     * @param taoBaoOrderJsonFromRds
     * @param topTrade
     * @return
     */
    private List<TopOrder> getTopOrdersFromJson(TaoBaoOrder taoBaoOrderJsonFromRds, TopTrade topTrade) {
        Trade trade = taoBaoOrderJsonFromRds.getTaoBaoResponse().getTrade_fullinfo_get_response().getTrade();
        List<TopOrder> list = new ArrayList<TopOrder>();
        List<cn.rkylin.oms.order.vo.Order> listOrder = trade.getOrders();
        // 日期格式化
        try {
            if (listOrder == null || listOrder.size() <= 0) {
                return null;
            }

            for (int i = 0; i < listOrder.size(); i++) {
                TopOrder topOrder = new TopOrder();
                topOrder.setTopTradeId(topTrade.getTopTradeId());
                topOrder.setTid(topTrade.getTid());
                topOrder.setAdjustFee(listOrder.get(i).getAdjust_fee());
                topOrder.setBuyerRate("true".equals(listOrder.get(i).getBuyer_rate()) ? Integer.valueOf(1) : Integer.valueOf(0));
                topOrder.setCid(listOrder.get(i).getCid());
                topOrder.setDiscountFee(listOrder.get(i).getDiscount_fee());
                topOrder.setIsDaixiao("true".equals(listOrder.get(i).getIs_daixiao()) ? Integer.valueOf(1) : Integer.valueOf(0));
                topOrder.setIsOversold("true".equals(listOrder.get(i).getIs_oversold()) ? Integer.valueOf(1) : Integer.valueOf(0));
                topOrder.setNum(listOrder.get(i).getNum());
                topOrder.setNumIid(listOrder.get(i).getNum_iid());
                topOrder.setOid(listOrder.get(i).getOid());
                topOrder.setOrderFrom(listOrder.get(i).getOrder_from());
                topOrder.setOuterIid(listOrder.get(i).getOuter_iid());
                topOrder.setOuterSkuId(listOrder.get(i).getOuter_sku_id());
                topOrder.setPartMjzDiscount(listOrder.get(i).getPart_mjz_discount());
                topOrder.setPayment(listOrder.get(i).getPayment());
                topOrder.setPicPath(listOrder.get(i).getPic_path());
                topOrder.setPrice(listOrder.get(i).getPrice());
                topOrder.setRefundStatus(listOrder.get(i).getRefund_status());
                topOrder.setSellerRate("true".equals(listOrder.get(i).getSeller_rate()) ? Integer.valueOf(1) : Integer.valueOf(0));
                topOrder.setSellerType(listOrder.get(i).getSeller_type());
                topOrder.setSkuId(listOrder.get(i).getSku_id() == null ? 0 : listOrder.get(i).getSku_id());
                topOrder.setSkuPropertiesName(listOrder.get(i).getSku_properties_name());
                topOrder.setSnapshotUrl(listOrder.get(i).getSnapshot_url());
                topOrder.setStatus(listOrder.get(i).getStatus());
                topOrder.setTitle(listOrder.get(i).getTitle());
                topOrder.setTotalFee(listOrder.get(i).getTotal_fee());
                topOrder.setDivideOrderFee(listOrder.get(i).getDivide_order_fee());
                topOrder.setLogisticsCompany(listOrder.get(i).getLogistics_company());
                topOrder.setInvoiceNo(listOrder.get(i).getInvoice_no());
                list.add(topOrder);
            }

        } catch (Exception ex) {
            logUtil.error(new DBLog(topTrade.getTid().toString(), "从Json中获取获取TopOrders", "自动下载淘宝订单", "getTopOrdersFromJson方法异常：" + ex.getMessage()), ex);
            return null;
        }
        return list;
    }


    /**
     * 保存TopOrders
     *
     * @param list
     * @return
     */
    private int saveTopOrders(TopTrade topTrade, List<TopOrder> list) {
        if (list == null || list.size() <= 0) {
            return 0;
        }

        for (TopOrder topOrder : list) {
            try {
                TopOrder exitTopOrder = (TopOrder) dao.find("selectByOidTopOrder", topOrder.getOid());
                if (exitTopOrder == null) {
                    topOrder.setSellerNick(topTrade.getSellerNick());
                    topOrder.setBuyerNick(topTrade.getBuyerNick());
                    topOrder.setTopOrderId(java.util.UUID.randomUUID().toString().replaceAll("-", ""));
                    dao.insert("insertSelectiveTopOrder", topOrder);
                } else {
                    dao.update("updateByOid", topOrder);
                }
            } catch (Exception ex) {
                logUtil.error(new DBLog(topOrder.getTid().toString(), "保存TopOrders", "自动下载淘宝订单", "saveTopOrders方法异常：" + ex.getMessage()), ex);
                continue;
            }
        }

        return list.size();
    }

    /**
     * 保存EcTrade到数据库
     *
     * @param listTopTradeOrder
     * @param shop
     * @return
     */
    private int saveEcData(List<TopTradeOrder> listTopTradeOrder, Shop shop) {
        // 循环订单记录
        for (TopTradeOrder topTradeOrder : listTopTradeOrder) {
            try {
                // 取得当前的订单信息
                TopTrade topTrade = topTradeOrder.getTopTrade();

                // 取得相应的订单的商品信息
                List<TopOrder> listOrder = topTradeOrder.getListTopOrder();

                // 原始数据，也就是父节点的数据
                EcTrade ecTrade = getEcTrade(topTrade,shop);

                // 处理EcTrade
                Map<String, Object> reqMap = new HashMap<String, Object>();
                reqMap.put("ecTradeCode", topTrade.getTid());
                reqMap.put("shopId", ecTrade.getShopId());
                EcTrade ecTradeExists = orderServiceImpl.selectByEcTradeCodeAndShopIdEcTrade(reqMap);

                if (ecTradeExists == null) {
                    taobaoTradeService.insert("insertSelectiveEcTrade", ecTrade);
                } else {
                    // 更新oms_ec_trade
                    ecTrade.setEcTradeId(ecTradeExists.getEcTradeId());
                    taobaoTradeService.update("updateByPrimaryKeySelectiveEcTrade", ecTrade);
                }

                // 处理EcOrder
                for (TopOrder topOrder : listOrder) {
                    // 获取转换后的EcOrder
                    EcOrder ecOrder = getEcOrder(topOrder, ecTrade.getEcTradeId());

                    EcOrder param = new EcOrder();
                    param.setEcTradeCode(ecTrade.getEcTradeCode());
                    param.setShopId(ecTrade.getShopId());
                    param.setEcOid(topOrder.getOid());
                    EcOrder ecOrderExists = (EcOrder) dao.find("selectByUniqKey", param);

                    if (ecOrderExists == null) {
                        ecOrder.setShopId(ecTrade.getShopId());
                        ecOrder.setEcTradeCode(ecTrade.getEcTradeCode());
                        taobaoOrderService.insert("insertSelectiveEcOrder", ecOrder);
                    } else {
                        ecOrder.setEcOrderId(ecOrderExists.getEcOrderId());
                        taobaoOrderService.update("updateByPrimaryKeySelectiveEcOrder", ecOrder);
                    }
                }
            } catch (Exception ex) {
                logUtil.error(new DBLog(topTradeOrder.getTopTrade().getTid().toString(), "保存EcTrade到数据库", "自动下载淘宝订单", "saveEcData：" + ex.getMessage()), ex);
                continue;
            }
        }

        return 1;
    }

    /**
     * oms_ec_trade数据准备
     *
     * @param topTrade
     * @param shop
     * @return
     */
    private EcTrade getEcTrade(TopTrade topTrade, Shop shop) throws Exception {
        EcTrade trade = new EcTrade();
        trade.setEcTradeId(java.util.UUID.randomUUID().toString().replaceAll("-", ""));
        trade.setParentTradeId(trade.getEcTradeId());
        // shop赋值
        trade.setShop(shop);
        trade.setEcTradeCode(topTrade.getTid().toString());
        trade.setEcCustCode(taobaoEncrypt.decript(topTrade.getBuyerNick(),"simple"));
        trade.setEcCustName(taobaoEncrypt.decript(topTrade.getBuyerNick(),"simple"));
        trade.setPrjId(shop.getPrjId());
        trade.setPrjName(shop.getPrjName());
        trade.setShopId(shop.getShopId());
        trade.setShopName(shop.getShopName());
        trade.setShopAccount(shop.getShopAccount());
        trade.setShopType(shop.getShopType());
        trade.setBuyerAlipayNo(taobaoEncrypt.decript(topTrade.getBuyerAlipayNo(),"simple"));
        // 性能改造 area走缓存
        trade.setAreaCoding(getAreaCode(topTrade.getReceiverState(), topTrade.getReceiverCity(), topTrade.getReceiverDistrict()));
        trade.setProvName(topTrade.getReceiverState());
        trade.setCityName(topTrade.getReceiverCity());
        trade.setDistName(topTrade.getReceiverDistrict());
        if (this.isTest) {
            trade.setEcTradeStatus("EC_WAIT_SELLER_SEND");
        } else {
            trade.setEcTradeStatus(OrderStatusMap.statusMap.get(topTrade.getStatus()));
        }
        trade.setCons(taobaoEncrypt.decript(topTrade.getReceiverName(),"simple"));
        trade.setConsTel(taobaoEncrypt.decript(topTrade.getReceiverPhone(),"simple"));
        trade.setConsMobile(taobaoEncrypt.decript(topTrade.getReceiverMobile(),"phone"));
        String province = "";
        String city = "";
        String district = "";
        if (StringUtils.isNotBlank(topTrade.getReceiverState())) {
            province = topTrade.getReceiverState();
        }
        if (StringUtils.isNotBlank(topTrade.getReceiverCity())) {
            city = topTrade.getReceiverCity();
        }
        if (StringUtils.isNotBlank(topTrade.getReceiverDistrict())) {
            district = topTrade.getReceiverDistrict();
        }
        trade.setConsAddr(province + city + district + taobaoEncrypt.decript(topTrade.getReceiverAddress(),"simple"));
        trade.setConsPostCode(topTrade.getReceiverZip());
        trade.setCustRemark(topTrade.getBuyerMessage());
        trade.setPaidFee(topTrade.getPayment() != null ? new BigDecimal(topTrade.getPayment()) : null);
        trade.setLgstFee(topTrade.getPostFee());
        trade.setTradeMoney(topTrade.getTotalFee());
        trade.setPaidTime(topTrade.getPayTime());
        trade.setEndTime(topTrade.getEndTime());
        trade.setOrderTime(topTrade.getCreated());
        trade.setConsignTime(topTrade.getConsignTime());
        trade.setSalesRemark(topTrade.getSellerMemo());
        trade.setSellerFlag(topTrade.getSellerFlag());
        return trade;
    }

    /**
     * oms_ec_order数据准备
     *
     * @param topOrder
     * @param ecTradeId
     * @return
     */
    private EcOrder getEcOrder(TopOrder topOrder, String ecTradeId) throws Exception {
        EcOrder ecOrder = new EcOrder();

        ecOrder.setEcOrderId(java.util.UUID.randomUUID().toString().replaceAll("-", ""));
        ecOrder.setTopOrderId(topOrder.getTopOrderId());
        ecOrder.setEcTradeId(ecTradeId);
        ecOrder.setEcOid(topOrder.getOid());
        ecOrder.setEcItemCode(topOrder.getNumIid().toString());
        ecOrder.setEcItemName(topOrder.getTitle());
        ecOrder.setEcSkuCode(topOrder.getSkuId() != null ? topOrder.getSkuId().toString() : null);
        ecOrder.setRefundStatus(RefundStatusMap.statusMap.get(topOrder.getRefundStatus()));
        ecOrder.setDivideOrderFee(topOrder.getDivideOrderFee());
        // 平台无规格，上商品名称
        if(!StringUtils.isEmpty(topOrder.getSkuPropertiesName())) {
            ecOrder.setEcSkuName(topOrder.getSkuPropertiesName());
        }else{
            ecOrder.setEcSkuName(topOrder.getTitle());
        }
        ecOrder.setQty(topOrder.getNum());
        if (topOrder.getTotalFee() != null && topOrder.getNum() != null && topOrder.getNum().intValue() != 0) {
            ecOrder.setFactUnitPrice(
                    topOrder.getTotalFee().divide(BigDecimal.valueOf(topOrder.getNum()), 2, RoundingMode.HALF_UP));
        }
        ecOrder.setStanUnitPrice(topOrder.getPrice());
        ecOrder.setDiscountFee(topOrder.getDiscountFee());
        ecOrder.setAdjustFee(topOrder.getAdjustFee());
        ecOrder.setLgstName(topOrder.getLogisticsCompany());
        ecOrder.setLgstNo(topOrder.getInvoiceNo());
        Date date = new Date();
        ecOrder.setUpdateTime(date);
        ecOrder.setDeleted("n");
        if (this.isTest) {
            ecOrder.setEcOrderStatus("EC_WAIT_SELLER_SEND");
        } else {
            ecOrder.setEcOrderStatus(OrderStatusMap.statusMap.get(topOrder.getStatus()));
        }
        return ecOrder;
    }


    /**
     * 获取地区码
     *
     * @param prov
     * @param city
     * @param dist
     * @return
     */
    private String getAreaCode(String prov, String city, String dist) {
        prov = StringUtils.trimToEmpty(prov);
        city = StringUtils.trimToEmpty(city);
        dist = StringUtils.trimToEmpty(dist);

        String areaCode;
        try {
            areaCode = AREA_CODE_MAP_CACHE.get(prov + ":" + city + ":" + dist);
            if (StringUtils.isNotBlank(areaCode)) {
                return areaCode;
            } else {
                logUtil.info(new DBLog("", "未能从缓存里匹配到地区码", "自动下载淘宝订单", prov + ":" + city + ":" + dist));
                return "0";
            }
        } catch (Exception ex) {
            logUtil.error(new DBLog("", "从缓存里匹配地区码出错", "自动下载淘宝订单", ex.getMessage()), ex);
            return "0";
        }

    }

    /**
     * 平台发货
     *
     * @param shopId        店铺id
     * @param dateTimeStart 开始时间
     * @param dateTimeEnd   结束时间
     * @throws Exception 异常
     */
    public Map<String, Object> consign(String shopId, String dateTimeStart, String dateTimeEnd) throws Exception {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        Map<String, Object> returnMap = new HashMap<String, Object>();
        ShopVO shopVO = getShop(shopId);
        // shop取得失败的时候，返回
        if (shopVO == null) {
            returnMap.put("success", "false");
            returnMap.put("msg", "ShopVO is null");
            return returnMap;
        }
        // 如果未开启自动平台发货开关
        if ("n".equals(shopVO.getIsAutoPlatformDelivery())) {
            returnMap.put("success", "false");
            returnMap.put("msg", "未开启自动平台发货开关");
            return returnMap;
        }
        paramMap.put("shop", shopVO);
        // 设置参数
        if (StringUtils.isNotBlank(dateTimeStart)) {
            paramMap.put("startTime", dateTimeStart);
        }
        if (StringUtils.isNotBlank(dateTimeEnd)) {
            paramMap.put("endTime", dateTimeEnd);
        }
        long startTime = System.currentTimeMillis();
        returnMap = this.getOrderVisitor().consign(paramMap);
        //logger.error(">>>>>>>>>>>> 平台发货:" + (System.currentTimeMillis() - startTime) + "<<<<<<<<<<<");
        return returnMap;
    }

}